/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Struts2Utils.java,v 1.3 2012/03/02 06:46:49 zwm Exp $
 */
package com.pengtu.utils.web;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;

import com.pengtu.Constants;

/**
 * Struts2工具类. 
 * 
 * 实现获取Request/Response/Session与绕过jsp/freemaker直接输出文本的简化函数.
 * 
 * @author calvin
 */
public class Struts2Utils {

	//-- header 常量定义 --//
	private static final String HEADER_ENCODING = "encoding";
	private static final String HEADER_NOCACHE = "no-cache";
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final boolean DEFAULT_NOCACHE = true;

	private static ObjectMapper mapper = new ObjectMapper();

	//-- 取得Request/Response/Session的简化函数 --//
	/**
	 * 取得HttpSession的简化函数.
	 */
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 取得HttpSession的简化函数.
	 */
	public static HttpSession getSession(boolean isNew) {
		return ServletActionContext.getRequest().getSession(isNew);
	}

	/**
	 * 取得HttpSession中Attribute的简化函数.
	 */
	public static Object getSessionAttribute(String name) {
		HttpSession session = getSession(false);
		return (session != null ? session.getAttribute(name) : null);
	}

	/**
	 * 取得HttpSession中Attribute的简化函数.
	 */
	public static void setSessionAttribute(String name,Object value) {
		HttpSession session = getSession(false);
		if(session != null)  session.setAttribute(name, value);
	}

	/**
	 * 取得HttpRequest的简化函数.
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 取得HttpRequest中Parameter的简化方法.
	 */
	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	/**
	 * 取得HttpResponse的简化函数.
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	
	/**
	 * 跳转到URL页面 
	 * @throws IOException 
	 */
	public static void sendRedirectUrl(String url) throws IOException {
		String  targetUrl = URLDecoder.decode(url, "UTF-8");
		RedirectStrategy defaultRedirectStrategy = new DefaultRedirectStrategy();
		defaultRedirectStrategy.sendRedirect(getRequest(), getResponse(), targetUrl);
	}
	
	/**
	 * 跳转回原来页面  使用sendRedirect  重定向
	 * sendRefererUrl:
	 * 适用:
	 * @throws IOException
	 * @throws ServletException 
	 * @exception 
	 * @since  1.0.0
	 */
	public static void sendRefererUrl() throws IOException, ServletException {
		sendRefererUrl(false);
	}
	
	/**
	 * 跳转回原来页面
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public static void sendRefererUrl(boolean useForward) throws IOException, ServletException {
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		String  targetUrl = request.getHeader("Referer");
		if(useForward) {
			RequestDispatcher dispatcher = request.getRequestDispatcher(targetUrl);
            dispatcher.forward(request, response);
		} else {
			RedirectStrategy defaultRedirectStrategy = new DefaultRedirectStrategy();
			defaultRedirectStrategy.sendRedirect(request, getResponse(), targetUrl);
		}
	}
	//-- 绕过jsp/freemaker直接输出文本的函数 --//
	/**
	 * 直接输出内容的简便函数.

	 * eg.
	 * render("text/plain", "hello", "encoding:GBK");
	 * render("text/plain", "hello", "no-cache:false");
	 * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
	 * 
	 * @param headers 可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(final String contentType, final String content, final String... headers) {
		HttpServletResponse response = initResponseHeader(contentType, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本.
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text, final String... headers) {
		render(ServletUtils.TEXT_TYPE, text, headers);
	}

	/**
	 * 直接输出HTML.
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html, final String... headers) {
		render(ServletUtils.HTML_TYPE, html, headers);
	}
	/**
	 * 获得web程序的在服务器上的发布路径
	 * ServletContext:
	 * 适用:
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static ServletContext getServletContext() {
		return getSession().getServletContext();
	}

	/**
	 * 直接输出XML.
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml, final String... headers) {
		render(ServletUtils.XML_TYPE, xml, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param jsonString json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String jsonString, final String... headers) {
		render(ServletUtils.JSON_TYPE, jsonString, headers);
	}

	/**
	 * 直接输出JSON,使用Jackson转换Java对象.
	 * 
	 * @param data 可以是List<POJO>, POJO[], POJO, 也可以Map名值对.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final Object data, final String... headers) {
		HttpServletResponse response = initResponseHeader(ServletUtils.JSON_TYPE, headers);
		try {
			mapper.writeValue(response.getWriter(), data);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	/**
	 * 获得ext store 所需要的json 字符串 形如
	 * "{'success':true,'totalCounts':0,'results':[]}"
	 * @param jsonArray
	 * @return
	 * 
	 * 631wj
	 * String
	 */
	 public static void renderJsontoExtTotalResults(Collection<?> dataArray,final String... headers){
		 	if(dataArray==null){
			  renderJson(Constants.EXT_LIST_JSON_STR,headers);
		 	}
            Map<String,Object> json = new HashMap<String,Object>();
            json.put(Constants.EXT_JSON_TOTALCOUNTS_STR, dataArray.size());        
            json.put(Constants.EXT_JSON_RESULTS_STR, dataArray);
            json.put(Constants.EXT_JSON_SUCCESS_STR, true);
            renderJson(json,headers);
	}
	/**
	 * 获得ext store 所需要的json 字符串 形如
	 * "{'success':true,'totalCounts':0,'results':[]}"
	 * @param jsonArray  当前的json数组
	 * @param totalcounts 实际条件中数据的总数
	 * @return
	 * 
	 * 631wj
	 * String
	 */
	public static void renderJsontoExtTotalResults(List<?> dataArray,Integer totalcounts,final String... headers){
		 if(dataArray==null){
			 renderJson(Constants.EXT_LIST_JSON_STR,headers);
		 }
		 if(totalcounts == null ){
			 totalcounts = dataArray.size();
		 }
            Map<String,Object> json = new HashMap<String,Object>();
            json.put(Constants.EXT_JSON_TOTALCOUNTS_STR, totalcounts);        
            json.put(Constants.EXT_JSON_RESULTS_STR, dataArray);
            json.put(Constants.EXT_JSON_SUCCESS_STR, true);
            renderJson(json,headers);
	}
	/**
	 * 获得ext store 所需要的json 字符串 形如
	 * "{'success':true,'data':{}}"
	 * @param jsonArray
	 * @return
	 * 
	 * 631wj
	 * String
	 */
	static public void renderJsontoExtOneData(Object data,final String... headers){
		 if(data==null){
			 renderJson(Constants.EXT_DATA_JSON_STR,headers);
		 }
		 	Map<String,Object> json = new HashMap<String,Object>();
            json.put(Constants.EXT_JSON_DATA_STR, data);
			json.put(Constants.EXT_JSON_SUCCESS_STR, true);
			renderJson(json,headers);
	}

	/**
	 * 直接输出支持跨域Mashup的JSONP.
	 * 
	 * @param callbackName callback函数名.
	 * @param object Java对象,可以是List<POJO>, POJO[], POJO ,也可以Map名值对, 将被转化为json字符串.
	 */
	public static void renderJsonp(final String callbackName, final Object object, final String... headers) {
		String jsonString = null;
		try {
			jsonString = mapper.writeValueAsString(object);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}

		String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");").toString();

		//渲染Content-Type为javascript的返回内容,输出结果为javascript语句, 如callback197("{html:'Hello World!!!'}");
		render(ServletUtils.JS_TYPE, result, headers);
	}

	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
		//分析headers参数
		String encoding = DEFAULT_ENCODING;
		boolean noCache = DEFAULT_NOCACHE;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}
		}

		HttpServletResponse response = ServletActionContext.getResponse();

		//设置headers参数
		String fullContentType = contentType + ";charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			ServletUtils.setDisableCacheHeader(response);
		}

		return response;
	}

	/**
	 * 获得web程序的在服务器上的发布路径
	 * getAppRootPath:
	 * 适用:
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String getAppRootPath() {
		return getServletContext().getRealPath("/").toString();
	}
	
	
	/**
	 * 获得web程序的classpath--localhost:8080/项目名称
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 * */
	public static String getRootPath(){
		return getRequest().getContextPath();
	}
}
